package com.gnerv.battle.boot.project.guard.datasource;

import com.gnerv.battle.boot.common.tools.GsonTools;
import com.gnerv.battle.boot.project.guard.model.bo.MonitorDatasourceBO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.jdbc.DataSourceBuilder;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * @author Gnerv LiGen
 */
@Slf4j
public class MonitorDatasourceHandler {

    public boolean test(MonitorDatasourceBO monitorDatasourceBO){
        return switch (monitorDatasourceBO.getType()) {
            case "clickhouse" -> testClickhouse(monitorDatasourceBO);
            case "elasticsearch" -> testElasticsearch(monitorDatasourceBO);
            default -> false;
        };
    }

    public boolean testClickhouse(MonitorDatasourceBO monitorDatasourceBO){
        DataSource dataSource = createClickhouseDataSource(monitorDatasourceBO);
        try {
            dataSource.getConnection();
        } catch (SQLException e) {
            log.info(e.getMessage());
            return false;
        }
        return true;
    }

    public boolean testElasticsearch(MonitorDatasourceBO monitorDatasourceBO){
        return true;
    }

    public DataSource createClickhouseDataSource(MonitorDatasourceBO monitorDatasourceBO){
        String config = monitorDatasourceBO.getConfig();
        DatasourceClickhouse datasourceClickhouse = GsonTools.GSON.fromJson(config, DatasourceClickhouse.class);
        DataSourceBuilder<?> dataSourceBuilder = DataSourceBuilder.create();
        dataSourceBuilder.driverClassName("org.h2.Driver");
        dataSourceBuilder.url(datasourceClickhouse.getDataSourceName());
        return dataSourceBuilder.build();
    }

}
